import { isNil, omit } from "lodash";
import { MysqlDataSource } from "ROOT/db/orm";

import WatchEntity from "./watch.entity";
import StrategyService from 'ROOT/module/strategy/strategy.service';
import SymbolFactorService from '../symbol-factor/SymbolFactor.service';
import { defaultStrategy } from "ROOT/trader";

class WatchService {
  private repository = MysqlDataSource.getRepository(WatchEntity);

  /**
   * 查询
   * @param {object} query
   */
  find = async  (query: Record<string, any> = {}) => {
    const list = await this.repository.find({ relations: ['strategy'], where: query });
    const newList: (WatchEntity & { vector_count_15m: number, vector_count_4h: number })[] = []
    for (const item of list) {
      const count_15m = await SymbolFactorService.findCount({ symbol: item.symbol, period: '15m' });
      const count_4m = await SymbolFactorService.findCount({ symbol: item.symbol, period: '4h' });
      newList.push({
        ...item,
        vector_count_15m: count_15m,
        vector_count_4h: count_4m
      })
    }
    return newList;
  }

  /**
   * 查询单个
   * @param {object} query
   */
  findOne = async  (query: { id: number } | { symbol: string }) => {
    const target = await this.repository.findOne({ relations: ['strategy'], where: query });
    return target
  }

  /**
   * 更新单个
   * @param {object} query
   * @param { Document }
   */
  updateOne = async  (id: number, newData: Partial<WatchEntity>) => {
    if (newData.strategy && newData.strategy.id) {
      const strategyData = await StrategyService.update({
        id: newData.strategy.id,
        userid: 0,
      }, omit(newData.strategy, 'id'));
    }
    return await this.repository.update({ id: id }, newData);
  }

  /**
   * 删除单个
   * @param {object} query
   * @param { Document }
   */
  deleteOne = async  (id: number) => {
    const target = await this.repository.findOne({ where: { id } });
    if (!target) {
      return Promise.reject(`未找到${id}`);
    }
    try {
      target.strategy = null;
      target.strategy_id = null;
      await this.repository.save(target);
      const deleted = await this.repository.delete(id);
      if (isNil(deleted)) {
        return Promise.reject('删除出错');
      }
    } catch (error) {
      console.log(error)
    }

    return target;
  }

  /**
   * 新增
   * @param {object} query
   * @param { Document }
   */
  create = async  (data: Partial<WatchEntity>) => {

    const Doc = this.repository.create(data);
    return this.repository.save(Doc);
  }
  async unbindStrategy(id: number) {
    const list = await this.repository.find({ relations: ['strategy'], where: {} });
    for (const data of list) {
      if (data.strategy && data.strategy.id === id) {
        data.strategy = null;
        data.strategy_id = null;
        await this.repository.save(data);
      }
    }
  }
  async bindStrategy(id: number, strategyId: number) {
    const target = await this.findOne({id: id});
    const strategy = await StrategyService.findOne({id: strategyId});
    if (target && strategy) {
      target.strategy = strategy;
      target.strategy_id = strategy.id;
      await this.repository.save(target)
      return target
    } else {
      throw new Error('绑定失败');
    }
  }
}
export default new WatchService()